package com.huichaoliu.stylist.activity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.huichaoliu.app.R;
import com.huichaoliu.data.AES;
import com.huichaoliu.data.UserInfo;
import com.rederxu.farmer.BaseActivity;
import com.ta.util.http.AsyncHttpClient;
import com.ta.util.http.AsyncHttpResponseHandler;
import com.ta.util.http.RequestParams;

public class StylistMineUpdataActivity extends BaseActivity implements OnClickListener {

	// 用于请求和上传图片
	AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
	// 输入框dialog的输入框
	EditText inputServer;
	// 输入框dialog的dialog
	AlertDialog.Builder builder;

	// 当前Activity的大写字母合并+_UserInfo,用作显示当前用户信息,更改之后更新用户信息
	// 初始化在initData(),
	private UserInfo SMUA_userinfo;

	// 用户的密码,用于密码更改
	private String psd = "";

	// 用户提交头像地址
	private String headUrl = "http://211.149.205.68:8080/huichaoliu/service/action/updateuserimage.action";
	// 用户信息修改地址
	private String updateUrl = "http://211.149.205.68:8080/huichaoliu/service/action/updateuserinfo.action";

	public static final String[] PARTNER_START_PLACE = new String[] { "北京", "天津", "上海", "重庆", "河北", "山西", "辽宁", "吉林",
			"黑龙江", "江苏", "浙江", "安徽", "福建", "江西", "山东", "河南", "湖北", "湖南", "广东", "海南", "四川", "贵州", "云南", "陕西", "甘肃",
			"青海", "台湾", "内蒙古", "广西", "宁夏", "新疆", "西藏", "香港", "澳门", "海外" };

	private String[] starArr = { "魔羯座", "水瓶座", "双鱼座", "牡羊座", "金牛座", "双子座", "巨蟹座", "狮子座", "处女座", "天秤座", "天蝎座", "射手座" };

	/**
	 * 提交更改
	 */
	private void commitUserInfo() {
		RequestParams pms = new RequestParams();
		pms.put("request", getUpdateParmasJson());
		asyncHttpClient.post(headUrl, pms, new AsyncHttpResponseHandler() {

			// 请求开始
			@Override
			public void onStart() {
				super.onStart();
				Log.i("L:", "更新开始");
			}

			// 请求结束
			@Override
			public void onFinish() {
				super.onFinish();
				Log.i("L:", "更新结束");
			}

			// 成功
			@Override
			public void onSuccess(String content) {
				super.onSuccess(content);
				Log.i("L:", "更新信息返回数据: " + content);
			}

			// 失败
			@Override
			public void onFailure(Throwable error) {
				super.onFailure(error);
				Log.i("L:", "更新失败");
			}

		});
	}

	/**
	 * 上传头像
	 */
	private void updatePic() {
		if (tempFile == null) {
			showToast("无法读取头像图片文件");
			return;
		}
		RequestParams pms = new RequestParams();
		try {
			pms.put("file", tempFile);
			pms.put("request", getHeadParmasJson());
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			showToast("需要上传的图片文件不存在");
		}
		asyncHttpClient.post(headUrl, pms, new AsyncHttpResponseHandler() {

			// 请求开始
			@Override
			public void onStart() {
				super.onStart();
				Log.i("L:", "头像开始");
			}

			// 请求结束
			@Override
			public void onFinish() {
				super.onFinish();
				Log.i("L:", "头像结束");
				try {
					// 将临时文件删除
					tempFile.delete();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			// 成功
			@Override
			public void onSuccess(String content) {
				super.onSuccess(content);
				Log.i("L:", "头像成功: " + content);
			}

			// 失败
			@Override
			public void onFailure(Throwable error) {
				super.onFailure(error);
				Log.i("L:", "头像失败");
			}

		});
	}

	/**
	 * 获取头像修改的参数json,已经加密
	 * 
	 * @return
	 */
	private String getHeadParmasJson() {
		JSONObject jo = new JSONObject();
		try {
			jo.put("userId", SMUA_userinfo.getUid());
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log.i("L:", "头像参数json添加失败");
		}
		Log.i("L:", "头像参数: " + jo.toString());
		try {
			Log.i("L:", "头像参数加密成功");
			return AES.encrypt(jo.toString());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			Log.i("L:", "头像参数加密失败");
			e.printStackTrace();
			return "";
		}
	}

	/**
	 * 获取用户信息修改josn,已经加密
	 * 
	 * @return
	 */
	private String getUpdateParmasJson() {
		JSONObject jo = new JSONObject();
		try {
			jo.put("userId", SMUA_userinfo.getUid());
			jo.put("nickname", SMUA_userinfo.getNickname());
			jo.put("sex", SMUA_userinfo.getSex());
			jo.put("signature", SMUA_userinfo.getSignature());
			jo.put("age", SMUA_userinfo.getAge());
			jo.put("hobby", SMUA_userinfo.getHobby());
			jo.put("constellation", SMUA_userinfo.getConstellation());
			jo.put("area", SMUA_userinfo.getArea());
			jo.put("occupation", SMUA_userinfo.getOccupation());
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log.i("L:", "用户信息:" + jo.toString());
		}
		try {
			Log.i("L:", "用户信息加密成功");
			return AES.encrypt(jo.toString());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			Log.i("L:", "用户信息加密失败");
			e.printStackTrace();
			return "";
		}
	}

	private void changeHead() {
		// TODO 头像
		builder = new AlertDialog.Builder(this);
		builder.setItems(new String[] { "相册", "拍照", "取消" }, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				switch (which) {
				case 0:
					getPicForGallery(m_head);
					Log.i("L:", "选择了相册");
					break;
				case 1:
					getPicForCamera(m_head);
					Log.i("L:", "选择了拍照");
					break;
				case 2:
					dialog.dismiss();
					Log.i("L:", "用户取消");
					break;
				}
			}
		});
		builder.show();
	}

	private void changeUser() {
		// TODO 帐号
		inputServer = new EditText(this);
		builder = new AlertDialog.Builder(this);
		inputServer.setText(SMUA_userinfo.getUser());
		builder.setTitle("更改帐号").setView(inputServer).setNegativeButton("取消", null);
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				SMUA_userinfo.setUser(inputServer.getText().toString());
				Log.i("L:", "更改帐号" + inputServer.getText().toString());
				mchangeUser.setText(inputServer.getText().toString());
			}
		});
		builder.show();

	}

	private void changeSign() {
		// TODO 签名
		inputServer = new EditText(this);
		builder = new AlertDialog.Builder(this);
		inputServer.setText(SMUA_userinfo.getSignature());
		builder.setTitle("更改签名").setView(inputServer).setNegativeButton("取消", null);
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				SMUA_userinfo.setSignature(inputServer.getText().toString());
				Log.i("L:", "更改签名" + inputServer.getText().toString());
				m_changeSignature.setText(inputServer.getText().toString());
			}
		});
		builder.show();
	}

	private void changePsd() {
		// TODO 密码
		// inputServer.setText(SMUA_userinfo.get..StylistMineUpdataActivity...);//密码哪儿get?
		inputServer = new EditText(this);
		builder = new AlertDialog.Builder(this);
		inputServer.setText(psd);
		builder.setTitle("更改密码").setView(inputServer).setNegativeButton("取消", null);
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				psd = inputServer.getText().toString();
				Log.i("L:", "更改密码" + inputServer.getText().toString());
				// mchange.setText(inputServer.getText().toString());
			}
		});
		builder.show();

	}

	private void changeOcc() {
		// TODO 那啥zy
		inputServer = new EditText(this);
		builder = new AlertDialog.Builder(this);
		inputServer.setText(SMUA_userinfo.getOccupation());
		builder.setTitle("更改职业").setView(inputServer).setNegativeButton("取消", null);
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				Log.i("L:", "更改职业" + inputServer.getText().toString());
				SMUA_userinfo.setOccupation(inputServer.getText().toString());
				mchangeOccupation.setText(inputServer.getText().toString());
			}
		});
		builder.show();

	}

	private void changeNickname() {
		// TODO 昵称
		inputServer = new EditText(this);
		builder = new AlertDialog.Builder(this);
		inputServer.setText(SMUA_userinfo.getNickname());
		builder.setTitle("更改昵称").setView(inputServer).setNegativeButton("取消", null);
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				Log.i("L:", "更改昵称" + inputServer.getText().toString());
				SMUA_userinfo.setNickname(inputServer.getText().toString());
				mchangeNickname.setText(inputServer.getText().toString());
			}
		});
		builder.show();

	}

	private void changeHby() {
		// TODO 爱好
		inputServer = new EditText(this);
		builder = new AlertDialog.Builder(this);
		inputServer.setText(SMUA_userinfo.getHobby());
		builder.setTitle("更改爱好").setView(inputServer).setNegativeButton("取消", null);
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				Log.i("L:", "更改爱好" + inputServer.getText().toString());
				SMUA_userinfo.setHobby(inputServer.getText().toString());
				mchangeHobby.setText(inputServer.getText().toString());
			}
		});
		builder.show();

	}

	private void changeCons() {
		// TODO 那啥xz
		inputServer = new EditText(this);
		builder = new AlertDialog.Builder(this);
		inputServer.setText(SMUA_userinfo.getConstellation());
		builder.setTitle("更改星座");
		builder.setItems(starArr, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				Log.i("L:", "更改星座" + starArr[which]);
				SMUA_userinfo.setConstellation(starArr[which]);
				mchangeConstellation.setText(starArr[which]);
			}
		});
		builder.show();
	}

	private void changeArea() {
		// TODO 地区
		builder = new AlertDialog.Builder(this);
		builder.setTitle("更改地区");
		builder.setItems(PARTNER_START_PLACE, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				Log.i("L:", "更改地区" + PARTNER_START_PLACE[which]);
				SMUA_userinfo.setArea(PARTNER_START_PLACE[which]);
				mchangeArea.setText(PARTNER_START_PLACE[which]);
			}
		});
		builder.show();
	}

	// tools
	Context context;
	// views
	ImageView mine_icon;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.stylist_mine_updata_layout);
		super.onCreate(savedInstanceState);
	}

	/*
	 * Exceptions found during parsing
	 * 
	 * References a layout (@layout/stylist_title_bar)
	 */

	// Content View Elements

	/* 背景******** */
	private ImageView mStylist_mine_icon_bg;
	// 小头像
	private ImageView m_head;
	// 签名
	private TextView m_changeSignature;
	// 昵称
	private LinearLayout m_changeNickname;
	private TextView mchangeNickname;
	// 用户
	private LinearLayout m_changeUser;
	private TextView mchangeUser;
	// 密码
	private TextView m_changePsd;
	// 爱好
	private LinearLayout m_changeHobby;
	private TextView mchangeHobby;
	// 地区
	private LinearLayout m_changeArea;
	private TextView mchangeArea;
	// 那啥 xz
	private LinearLayout m_changeConstellation;
	private TextView mchangeConstellation;
	// 这啥 zy
	private LinearLayout m_changeOccupation;
	private TextView mchangeOccupation;

	// End Of Content View Elements

	private void bindViews() {

		mStylist_mine_icon_bg = (ImageView) findViewById(R.id.stylist_mine_icon_bg);
		m_head = (ImageView) findViewById(R.id._head);
		m_changeSignature = (TextView) findViewById(R.id._changeSignature);
		m_changeNickname = (LinearLayout) findViewById(R.id._changeNickname);
		m_changeUser = (LinearLayout) findViewById(R.id._changeUser);
		m_changePsd = (TextView) findViewById(R.id._changePsd);
		m_changeHobby = (LinearLayout) findViewById(R.id._changeHobby);
		m_changeArea = (LinearLayout) findViewById(R.id._changeArea);
		m_changeConstellation = (LinearLayout) findViewById(R.id._changeConstellation);
		m_changeOccupation = (LinearLayout) findViewById(R.id._changeOccupation);
		mchangeNickname = (TextView) findViewById(R.id.changeNickname);
		mchangeUser = (TextView) findViewById(R.id.changeUser);
		mchangeHobby = (TextView) findViewById(R.id.changeHobby);
		mchangeArea = (TextView) findViewById(R.id.changeArea);
		mchangeConstellation = (TextView) findViewById(R.id.changeConstellation);
		mchangeOccupation = (TextView) findViewById(R.id.changeOccupation);
	}

	@Override
	public void init() {
		context = this;
		findViewById(R.id.stylist_back).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				finish();
			}
		});
		((TextView) findViewById(R.id.stylist_name)).setText("");

		mine_icon = (ImageView) findViewById(R.id.stylist_mine_icon_bg);
		// LayoutParams parmas = mine_icon.getLayoutParams();
		// parmas.height = getPhoneWidth();
		// mine_icon.setLayoutParams(parmas);
		bindViews();
	}

	@Override
	public void initData() {
		// TODO

		if (SMUA_userinfo == null) { // 初始化,防止null
			Log.i("L:", "初始SMUA_....");
			SMUA_userinfo = new UserInfo(this);
			SMUA_userinfo.setAge(0);
			SMUA_userinfo.setArea("");
			SMUA_userinfo.setAvatar("");
			SMUA_userinfo.setCollocationNumber(0);
			SMUA_userinfo.setConstellation("");
			SMUA_userinfo.setFirstLogin(true);
			SMUA_userinfo.setMobile("0");
			SMUA_userinfo.setNickname("");
			SMUA_userinfo.setOccupation("");
			SMUA_userinfo.setSex("");
			SMUA_userinfo.setSignature("");
			SMUA_userinfo.setType(0);
			SMUA_userinfo.setUid("");
			SMUA_userinfo.setUser("");
		}

		m_head.setOnClickListener(this);
		m_changeSignature.setOnClickListener(this);
		m_changeNickname.setOnClickListener(this);
		m_changeUser.setOnClickListener(this);
		m_changePsd.setOnClickListener(this);
		m_changeHobby.setOnClickListener(this);
		m_changeArea.setOnClickListener(this);
		m_changeConstellation.setOnClickListener(this);
		m_changeOccupation.setOnClickListener(this);
	}

	@Override
	public void onNetworkChanged(boolean isMobNetConnected, boolean isWifiConnected) {
		// TODO

	}

	private static final int PHOTO_REQUEST_CAREMA = 1;// 拍照
	private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
	private static final int PHOTO_REQUEST_CUT = 3;// 结果
	/* 头像名称 */
	private static final String PHOTO_FILE_NAME = "temp_photo.jpg";
	private File tempFile;

	/**
	 * 从相册获取
	 */
	public void getPicForGallery(View view) {
		// 激活系统图库，选择一张图片
		Intent intent = new Intent(Intent.ACTION_PICK);
		intent.setType("image/*");
		// 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_GALLERY
		startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
	}

	/**
	 * 从相机获取
	 */
	public void getPicForCamera(View view) {
		// 激活相机
		Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
		// 判断存储卡是否可以用，可用进行存储
		if (hasSdcard()) {
			tempFile = new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME);
			// 从文件中创建uri
			Uri uri = Uri.fromFile(tempFile);
			intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
		}
		// 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CAREMA
		startActivityForResult(intent, PHOTO_REQUEST_CAREMA);
	}

	/**
	 * 剪切图片
	 */
	private void crop(Uri uri) {
		// 裁剪图片意图
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		// 裁剪框的比例，1：1
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// 裁剪后输出图片的尺寸大小
		intent.putExtra("outputX", 500);
		intent.putExtra("outputY", 500);

		intent.putExtra("outputFormat", "JPEG");// 图片格式
		intent.putExtra("noFaceDetection", true);// 取消人脸识别
		intent.putExtra("return-data", true);
		// 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CUT
		startActivityForResult(intent, PHOTO_REQUEST_CUT);
	}

	/**
	 * 判断sdcard是否被挂载
	 */
	private boolean hasSdcard() {
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == PHOTO_REQUEST_GALLERY) {
			// 从相册返回的数据
			if (data != null) {
				// 得到图片的全路径
				Uri uri = data.getData();
				crop(uri);
			}
		} else if (requestCode == PHOTO_REQUEST_CAREMA) {
			// 从相机返回的数据
			if (hasSdcard()) {
				crop(Uri.fromFile(tempFile));
			} else {
				Toast.makeText(StylistMineUpdataActivity.this, "未找到存储卡，无法存储照片！", Toast.LENGTH_SHORT).show();
			}
		} else if (requestCode == PHOTO_REQUEST_CUT) {
			// 从剪切图片返回的数据
			if (data != null) {
				Bitmap bitmap = data.getParcelableExtra("data");
				this.m_head.setImageBitmap(bitmap);
				saveBitmap(bitmap);
				updatePic();
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private int getPhoneWidth() {
		DisplayMetrics dm = new DisplayMetrics();
		((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(dm);
		int phoneDensity1 = dm.widthPixels;
		int height = (int) (phoneDensity1 * 0.6);
		return height;
	}

	@Override
	public void onClick(View v) {
		// TODO 点击事件
		switch (v.getId()) {
		case R.id._changeArea:
			changeArea();
			break;
		case R.id._changeConstellation:
			changeCons();
			break;
		case R.id._changeHobby:
			changeHby();
			break;
		case R.id._changeNickname:
			changeNickname();
			break;
		case R.id._changeOccupation:
			changeOcc();
			break;
		case R.id._changePsd:
			changePsd();
			break;
		case R.id._changeSignature:
			changeSign();
			break;
		case R.id._changeUser:
			changeUser();
			break;
		case R.id._head:
			changeHead();
			break;
		}
	}

	/**
	 * 保存bitmap为图片文件
	 * 
	 * @param bitmap
	 * @param bitName
	 * @throws IOException
	 */
	private void saveBitmap(Bitmap bitmap) {
		// TODO 保存图片
		tempFile = new File(Environment.getExternalStorageDirectory().getPath(), "temp_hcl.png");
		Log.i("L:", "文件: " + tempFile.getPath());

		if (tempFile.exists()) {
			tempFile.delete();
		}
//		if (!tempFile.canWrite()) {
//			Log.i("L:", "SD无法写入");
//			showToast("SD卡无法写入");
//			return;
//		}
		FileOutputStream out;
		try {
			out = new FileOutputStream(tempFile);
			if (bitmap.compress(Bitmap.CompressFormat.PNG, 90, out)) {
				out.flush();
				out.close();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			Log.i("L:", "文件不存在");
			showToast("文件不存在");
		} catch (IOException e) {
			e.printStackTrace();
			Log.i("L:", "SD卡异常");
			showToast("SD卡异常,无法缓存头像图片");
		}
	}
}
